package com.lianjia.crawler.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 数据加载工具类，用于加载USER_AGENTS和CITY_CODE数据
 */
public class DataLoader {
    private static final Logger logger = LoggerFactory.getLogger(DataLoader.class);
    private static final Random random = new Random();
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    private static List<String> userAgents;
    private static Map<String, String> cityCodes;
    
    /**
     * 加载USER_AGENTS数据
     * 
     * @return USER_AGENTS列表
     */
    public static List<String> loadUserAgents() {
        if (userAgents == null) {
            try (InputStream is = DataLoader.class.getClassLoader().getResourceAsStream("data/USER_AGENTS.json")) {
                userAgents = objectMapper.readValue(is, new TypeReference<List<String>>() {});
                logger.info("成功加载 {} 个User-Agent", userAgents.size());
            } catch (IOException e) {
                logger.error("加载USER_AGENTS.json失败", e);
                throw new RuntimeException("加载USER_AGENTS.json失败", e);
            }
        }
        return userAgents;
    }
    
    /**
     * 加载CITY_CODE数据
     * 
     * @return CITY_CODE映射
     */
    public static Map<String, String> loadCityCodes() {
        if (cityCodes == null) {
            try (InputStream is = DataLoader.class.getClassLoader().getResourceAsStream("data/CITY_CODE.json")) {
                cityCodes = objectMapper.readValue(is, new TypeReference<Map<String, String>>() {});
                logger.info("成功加载 {} 个城市代码", cityCodes.size());
            } catch (IOException e) {
                logger.error("加载CITY_CODE.json失败", e);
                throw new RuntimeException("加载CITY_CODE.json失败", e);
            }
        }
        return cityCodes;
    }
    
    /**
     * 随机获取一个User-Agent
     * 
     * @return 随机User-Agent
     */
    public static String getRandomUserAgent() {
        List<String> agents = loadUserAgents();
        return agents.get(random.nextInt(agents.size()));
    }
    
    /**
     * 获取城市代码
     * 
     * @param cityName 城市名称
     * @return 城市代码
     */
    public static String getCityCode(String cityName) {
        return loadCityCodes().get(cityName);
    }
    
    /**
     * 通过拼音或城市名获取城市代码
     * 
     * @param input 输入的拼音或城市名
     * @return 城市代码和城市名的数组，[0]为城市代码，[1]为城市名，如果未找到则返回null
     */
    public static String[] getCityCodeByPinyinOrName(String input) {
        Map<String, String> codes = loadCityCodes();
        
        // 直接匹配城市名
        if (codes.containsKey(input)) {
            return new String[]{codes.get(input), input};
        }
        
        // 匹配拼音代码
        for (Map.Entry<String, String> entry : codes.entrySet()) {
            if (entry.getValue().equalsIgnoreCase(input)) {
                return new String[]{entry.getValue(), entry.getKey()};
            }
        }
        
        return null;
    }

    /**
     * 获取所有城市代码
     * 
     * @return 城市代码Map，key为城市名，value为城市代码
     */
    public static Map<String, String> getAllCityCodes() {
        if (cityCodes == null) {
            loadCityCodes();
        }
        return new HashMap<>(cityCodes); // 返回副本，避免外部修改
    }
} 